<?php
declare(strict_types=1);

namespace App\Common\Command;

use Core\Basics\BasicsCommand;
use Hyperf\Command\Annotation\Command;
use Hyperf\DbConnection\Db;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

#[Command]
class ClearDbCommand extends BasicsCommand
{
    //要排除的数据
    const EXCLUDE = [
        'administer_department', 'administer_job', 'administer_log', 'administer_login_log', 'administer_menu', 'administer_role', 'administer_user',
        'applet', 'applet_renovation',
        'content_knowledge_classify', 'content_servers',
        'data_region', 'data_resources', 'data_resources_cate', 'data_search', 'data_sensitive',
        'lawyer_case_classify', 'lawyer_classify', 'lawyer_contract_classify', 'lawyer_epithet', 'lawyer_house', 'lawyer_recharge_rules', 'lawyer_recharge_vip',
        'store_goods_classify', 'store_goods_unit',
        'system_caching', 'system_configure', 'system_crontab', 'system_crontab_log', 'system_seo', 'system_sms', 'system_sms_template',
        'user_label', 'user_level', 'withdrawal_bank', 'applet_bind_gzh'
    ];

    /**
     * 执行的命令行
     *
     * @var null|string
     */
    protected ?string $name = 'app:clear-data';


    public function __construct(string $name = null)
    {
        parent::__construct($name);
        $this->setDescription('清空基本数据');
    }


    public function execute(InputInterface $input, OutputInterface $output): int
    {
        $choice = ['取消', '清空基本数据'];
        $handle = $this->choice('请选择操作', $choice, 0);
        switch ($handle) {
            case '清空基本数据';
                $this->clearData();
                break;
            case '取消';
                $this->output->warning('操作已取消');
                break;
        }
        return parent::execute($input, $output);
    }

    /**
     * 清空基本数据
     * @return void
     */
    protected function clearData(): void
    {
        $choice = ['取消操作', '继续操作'];
        $handle = $this->choice('确定要继续操作吗?数据删除后将不可恢复!', $choice, 0);
        switch ($handle) {
            case '继续操作';
                $tables = [];
                foreach (Db::select("SHOW TABLE STATUS") as $row) {
                    $tables[] = $row->Name;
                }
                /**
                 * 直接无条件删除数据库
                 * 高端的功能往往用最朴素的实现方法
                 */
                $this->output->success("开始清空数据......");
                foreach ($tables as $table) {
                    if (in_array($table, self::EXCLUDE)) {
                        continue;
                    }
                    Db::delete("DELETE FROM `{$table}`");
                    echo "{$table}已清空......" . PHP_EOL;
                }
                $this->output->success("数据清空完成");
                break;
            case '取消操作';
                $this->output->warning('操作已取消');
                break;
        }
    }
}